package office.poi.excel.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import office.utils.ObjectUtil;
import office.utils.StringUtil;

public class BeanUtils {
	public static void addValueToBean(String propertyName, Object value, Object beanClass)  {
		if (StringUtil.isNotEmpty(propertyName) && ObjectUtil.isNotEmpty(value)) {
			PropertyDescriptor pd;
			try {
				pd = new PropertyDescriptor(propertyName, beanClass.getClass());
				Class<?> clazz = pd.getPropertyType();
				//class java.lang.Character
				String clazzType = clazz.toString();
				if (clazzType.contains("Integer") || clazzType.contains("int")) {
					String val = value.toString();
					if(val.toString().contains("."))
					{
						val = val.substring(0, val.indexOf("."));
					}
					pd.getWriteMethod().invoke(beanClass,Integer.parseInt(val));
				} else if (clazzType.contains("Long")) {
					StringBuffer sb = new StringBuffer(value.toString());
					 
					if(sb.indexOf(".")>0){
						String s = sb.substring(0, sb.indexOf("."));
						pd.getWriteMethod().invoke(beanClass, Long.valueOf(s));
					}else{
						pd.getWriteMethod().invoke(beanClass, Long.valueOf(sb.toString()));
					}
				
					
					
				} else if (clazzType.contains("Double")) {
					pd.getWriteMethod().invoke(beanClass, Double.parseDouble(value.toString()));
				} else if (clazzType.contains("String")) {
					pd.getWriteMethod().invoke(beanClass, value.toString());
				} else if (clazzType.contains("Date")) {
					pd.getWriteMethod().invoke(beanClass, new SimpleDateFormat("yyyy/MM/dd").parse(value.toString()));
				}else if(clazzType.contains("Character"))
				{
					pd.getWriteMethod().invoke(beanClass, ObjectUtil.isNotEmpty(value)?value.toString().charAt(0) : null);
				}else if(clazzType.contains("Float"))
				{
					pd.getWriteMethod().invoke(beanClass, ObjectUtil.isNotEmpty(value)? Float.parseFloat(value.toString()):null);
				}
			} catch (IntrospectionException e) {
				e.printStackTrace();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		
		}
	}
}
